<template>
	<view class="page">
		<image src="/static/dingbu.png" class="mine-navbar-bg" :style="{ height: navbarHeight + 'rpx' }" mode="aspectFill"></image>
		<u-navbar title="机构审核详情" :autoBack="true" leftIconColor="#fff" bgColor="transparent" :titleStyle="{ color: '#fff' }"
			safeAreaInsetTop placeholder></u-navbar>
		<view style="height: 100rpx;"></view>
		<view class="content">
			<!-- 基础材料：逐条可展开 -->
			<view class="card">
				<u-collapse v-model="baseActive" :border="false">
					<u-collapse-item v-for="(item, idx) in baseList" :key="item.id" :name="item.id">
						<template #title>
							<view class="title-row">
								<text class="dot" v-if="item.required">*</text>
								<text class="idx">{{ idx + 1 }}.</text>
								<text class="txt">{{ item.text }}</text>
							</view>
						</template>
						<view class="item-body">
							<view class="files" v-if="item.files && item.files.length">
								<view v-for="(f, i) in item.files" :key="i" class="file-item" @click.stop="previewFile(f)">
									<u-icon name="file-text" size="18" color="#2d8cf0" class="mr-8" />
									<text class="file-link">{{ f }}</text>
								</view>
							</view>
							<view class="empty" v-else>暂无文件</view>
						</view>
					</u-collapse-item>
				</u-collapse>
			</view>

			<!-- 选择专家：可选择（组长单选、组员多选） -->
			<view class="card">
				<view class="section-title">选择专家</view>
				<view class="section-body">
					<view class="form-row selectable" @click="openLeaderDlg">
						<text class="label">评审组组长</text>
						<view class="value value-row">
							<text class="value-text">{{ leaderName || '请选择' }}</text>
							<u-icon name="arrow-right" size="16" color="#999" />
						</view>
					</view>
					<view class="form-row selectable" @click="openMemberDlg">
						<text class="label">评审组组员</text>
						<view class="value value-row">
							<text class="value-text">{{ memberNames.length ? memberNames.join('、') : '请选择' }}</text>
							<u-icon name="arrow-right" size="16" color="#999" />
						</view>
					</view>
				</view>
			</view>

			<!-- 专家评审：每条可展开 -->
			<view class="card">
				<view class="section-title">专家评审</view>
				<u-collapse v-model="reviewActive" :border="false">
					<u-collapse-item v-for="(rv, idx) in reviewItems" :key="rv.id" :name="rv.id">
						<template #title>
							<view class="title-row">
								<text class="idx">{{ idx + 1 }}、</text>
								<text class="txt">{{ rv.title }}</text>
							</view>
						</template>
						<view class="item-body">
							<view class="files" v-if="rv.files && rv.files.length">
								<view v-for="(f, i) in rv.files" :key="i" class="file-item" @click.stop="previewFile(f)">
									<u-icon name="file-text" size="18" color="#2d8cf0" class="mr-8" />
									<text class="file-link">{{ f }}</text>
								</view>
							</view>
							<view class="empty" v-else>暂无文件</view>
						</view>
					</u-collapse-item>
				</u-collapse>
			</view>
		</view>

		<!-- 组长选择弹窗（单选） -->
		<u-popup :show="showLeaderDlg" round mode="center" @close="showLeaderDlg=false">
			<view class="popup">
				<view class="popup-title">选择评审组组长</view>
				<u-radio-group v-model="leaderId" placement="column">
					<u-radio v-for="p in expertsList" :key="p.id" :name="p.id" :label="p.name" :customStyle="{margin:'8rpx 0', display:'block', width:'100%'}" />
				</u-radio-group>
				<view class="popup-actions">
					<u-button type="primary" size="small" @click="confirmLeader">确定</u-button>
					<u-button size="small" @click="showLeaderDlg=false">取消</u-button>
				</view>
			</view>
		</u-popup>

		<!-- 组员选择弹窗（多选） -->
		<u-popup :show="showMemberDlg" round mode="center" @close="showMemberDlg=false">
			<view class="popup">
				<view class="popup-title">选择评审组组员</view>
				<u-checkbox-group v-model="memberIds" placement="column">
					<u-checkbox v-for="p in expertsList" :key="p.id" :name="p.id" :label="p.name" :disabled="p.id===leaderId" :customStyle="{margin:'8rpx 0', display:'block', width:'100%'}" />
				</u-checkbox-group>
				<view class="popup-actions">
					<u-button type="primary" size="small" @click="confirmMembers">确定</u-button>
					<u-button size="small" @click="showMemberDlg=false">取消</u-button>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
// 移除对 tools.js 的依赖，预览逻辑内联
import navbarMixin from '@/common/navbarMixin'
export default {
	mixins: [navbarMixin],
	data() {
		return {
			// 基础材料默认展开第1条
			baseActive: ['1'],
			baseList: [
				{ id: '1', required: true, text: '机构法人资格证书或者其授权的证明文件', files: [] },
				{ id: '2', required: true, text: '上级或有关部门批准机构设置的证明文件', files: [] },
				{ id: '3', required: true, text: '质量体系文件（包括：质量手册、程序文件（全文）、作业指导书（目录））', files: [] },
				{ id: '4', required: false, text: '资质认定情况（证书、附表（电子版）、授权签字人及其授权签字领域表）', files: [] },
				{ id: '5', required: true, text: '近两年内的典型性检验报告（每个类别1份）', files: ['htxx.pdf', 'htxy.pdf'] }
			],
			experts: { leader: '路鹏', member: '路鹏' },
			// 选择专家
			showLeaderDlg: false,
			showMemberDlg: false,
			expertsList: [
				{ id: 'u1', name: '路鹏' },
				{ id: 'u2', name: '张三' },
				{ id: 'u3', name: '李四' },
				{ id: 'u4', name: '王五' }
			],
			leaderId: 'u1',
			memberIds: ['u1'],
			// 专家评审每条可展开
			reviewActive: ['r1'],
			reviewItems: [
				{ id: 'r1', title: '评审报告', files: ['评审报告.pdf', '补充说明.docx'] },
				{ id: 'r2', title: '评审记录表', files: ['评审记录表.pdf'] }
			]
		};
	},
	computed: {
		leaderName() { const f = this.expertsList.find(e=>e.id===this.leaderId); return f?f.name:'' },
		memberNames() {
			return this.memberIds
				.filter(id=>id!==this.leaderId)
				.map(id=>{ const f=this.expertsList.find(e=>e.id===id); return f?f.name:'' })
				.filter(Boolean)
		}
	},
	methods: {
		openLeaderDlg(){ this.showLeaderDlg = true },
		openMemberDlg(){ this.showMemberDlg = true },
		confirmLeader(){
			// 保证组长不在组员列表中
			this.memberIds = this.memberIds.filter(id=>id!==this.leaderId)
			this.showLeaderDlg = false
		},
		confirmMembers(){
			// 过滤掉组长
			this.memberIds = this.memberIds.filter(id=>id!==this.leaderId)
			this.showMemberDlg = false
		},
		// 解析文件名到可访问URL（示例映射 + 直链）
		resolveFileUrl(fileName) {
			if (!fileName) return ''
			if (/^https?:\/\//i.test(fileName)) return fileName
			const demoMap = {
				'评审报告.pdf': 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf',
				'评审记录表.pdf': 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf',
				'补充说明.docx': 'https://file-examples.com/storage/fe8d5f873d3a7bca6b55f18/2017/02/file-sample_100kB.docx'
			}
			if (demoMap[fileName]) return demoMap[fileName]
			return ''
		},
		getExt(url) { const m = (url || '').split('?')[0].match(/\.([a-z0-9]+)$/i); return m && m[1] ? m[1].toLowerCase() : '' },
		isImageExt(ext) { return ['png','jpg','jpeg','gif','bmp','webp','svg'].includes(ext) },
		mapFileType(ext) { const t = { pdf:'pdf', doc:'doc', docx:'docx', xls:'xls', xlsx:'xlsx', ppt:'ppt', pptx:'pptx', txt:'txt' }; return t[ext] || '' },
		tryOpenDocument(path, ext, withType = true) {
			return new Promise((resolve, reject) => { uni.openDocument({ filePath: path, fileType: withType ? this.mapFileType(ext) : '', showMenu: true, success: () => resolve(true), fail: (e) => reject(e) }) })
		},
		async downloadAndOpen(url, ext) {
			uni.showLoading({ title: '下载中', mask: true })
			try {
				const dl = await new Promise((resolve, reject) => {
					const task = uni.downloadFile({ url, success: res => res.statusCode === 200 ? resolve(res) : reject(res), fail: reject })
					try { task.onProgressUpdate && task.onProgressUpdate((p)=>{ if (p.progress%25===0) uni.showLoading({ title: '下载中 '+p.progress+'%', mask:true }) }) } catch(_){}
				})
				const temp = dl.tempFilePath
				try { await this.tryOpenDocument(temp, ext, true); uni.hideLoading(); return } catch(_) {}
				try { await this.tryOpenDocument(temp, ext, false); uni.hideLoading(); return } catch(_) {}
				const saved = await new Promise((resolve, reject) => { uni.saveFile({ tempFilePath: temp, success: resolve, fail: reject }) })
				try { await this.tryOpenDocument(saved.savedFilePath, ext, true); uni.hideLoading(); return } catch(_) {}
				try { await this.tryOpenDocument(saved.savedFilePath, ext, false); uni.hideLoading(); return } catch(_) {}
				// #ifdef APP-PLUS
				try { plus.runtime.openFile(saved.savedFilePath || temp); uni.hideLoading(); return } catch(e) { uni.showToast({ icon:'none', title:'无法打开文件' }) }
				// #endif
				uni.showToast({ icon:'none', title:'无法打开，请安装PDF/办公软件' })
			} catch (e) { uni.showToast({ icon:'none', title:'下载失败' }) }
			finally { uni.hideLoading() }
		},
		previewFile(name) {
			const url = this.resolveFileUrl(name)
			if (!url) { uni.showToast({ title: '暂无文件地址', icon: 'none' }); return }
			const ext = this.getExt(url)
			if (this.isImageExt(ext)) { uni.previewImage({ urls: [url] }); return }
			// #ifdef APP-PLUS
			this.downloadAndOpen(url, ext)
			// #endif
			// #ifndef APP-PLUS
			try { window.open(url, '_blank') } catch(e) { uni.showToast({ title: '请在App中预览', icon: 'none' }) }
			// #endif
		}
	}
}
</script>

<style lang="scss">
.page { min-height: 100vh; background: #f7f8fa; }
.mine-navbar-bg { position: fixed; top: 0; left: 0; width: 100%;  }
.content { padding: 24rpx 24rpx 40rpx; }
.card { background: #fff; border-radius: 16rpx; padding: 16rpx 20rpx; margin-bottom: 24rpx; box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.03); }
.section-title { font-size: 30rpx; font-weight: 600; color: #333; margin-bottom: 8rpx; }
.section-body { padding: 8rpx 4rpx 12rpx; }
.title-row { display: flex; align-items: flex-start; padding: 10rpx 0; line-height: 1.6; color: #333; font-size: 28rpx; }
.row { display: flex; align-items: flex-start; padding: 14rpx 0; line-height: 1.6; color: #333; font-size: 28rpx; }
.dot { color: #ff4d4f; margin-right: 8rpx; }
.idx { color: #999; margin: 0 8rpx 0 0; }
.txt { flex: 1; }
.item-body { padding: 8rpx 12rpx; }
.files { margin-top: 4rpx; }
.file-item { display: flex; align-items: center; padding: 10rpx 0; }
.file-link { color: #2d8cf0; }
.empty { color: #999; font-size: 26rpx; padding: 8rpx 0; }
.form-row { display: flex; justify-content: space-between; align-items: center; padding: 16rpx 0; font-size: 28rpx; color: #333; border-bottom: 1px solid #f0f0f0; }
.selectable { cursor: pointer; }
.value-row { display: inline-flex; align-items: center; gap: 8rpx; }
.value-text { max-width: 460rpx; text-align: right; color: #333; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
/* 弹窗样式 */
.popup { width: 640rpx; max-width: 90vw; padding: 24rpx; }
.popup-title { font-size: 30rpx; font-weight: 600; margin-bottom: 16rpx; }
.popup-actions { display: flex; justify-content: flex-end; gap: 16rpx; margin-top: 12rpx; }
</style>
